<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use think\db\exception\PDOException;
use think\exception\ValidateException;
use think\facade\Db;

/**
 * 做箱计划
 *
 */
class Conloadplan extends Backend
{
    /**
     * Conloadplan模型对象
     * @var \app\admin\model\Conloadplan
     */
    protected $model = null;
    protected $tz=null;
    protected $quickSearchField = ['CONLOADPLANID'];

    protected $defaultSortField = 'CONLOADPLANID,desc';

    protected $preExcludeFields = [''];
    protected $noNeedLogin      = ['*'];

    public function initialize()
    {
        parent::initialize();
        $this->model = new \app\admin\model\Conloadplan;
        $this->tz= new  \app\admin\model\Tz();
    }
    /**
     * 查看
     */
    public function index()
    {
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->param('select')) {
            $this->select();
        }

        list($where, $alias, $limit, $order) = $this->queryBuilder();
        $tzid=$this->request->get('tzid');
//        $tzid='LBLADM200600002';
        $wheres='';
        if(empty($where)){
            $wheres=" tzid='$tzid'";
        }
//var_dump($wheres);die;
        $res = $this->model
            ->field($this->indexField)
            ->withJoin($this->withJoinTable, $this->withJoinType)
            ->alias($alias)
            ->where($where)
            ->where($wheres)
            ->order($order)
            ->paginate($limit);

        $this->success('', [
            'list'   => $res->items(),
            'total'  => $res->total(),
            'remark' => get_route_remark(),
        ]);
    }
    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            if (!$data) {
                $this->error(__('Parameter %s can not be empty', ['']));
            }

            $data = $this->excludeFields($data);
            if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                $data[$this->dataLimitField] = $this->auth->id;
            }
            $sql="select  dbo.f_allow_truckno('$data[TZID]','$data[CNTRNO]','$data[TRUCKNO]') as status";
            $status=Db::query($sql)[0]['status'];

            if($status){
                $this->error('不能保存');
            }
            $result = false;
            Db::startTrans();
            try {
                // 模型验证
                if ($this->modelValidate) {
                    $validate = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                    if (class_exists($validate)) {
                        $validate = new $validate;
                        if ($this->modelSceneValidate) $validate->scene('add');
                        $validate->check($data);
                    }
                }
                $result = $this->model->save($data);
                Db::commit();
            } catch (ValidateException|PDOException|Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success(__('Added successfully'));
            } else {
                $this->error(__('No rows were added'));
            }
        }

        $this->error(__('Parameter error'));
    }
    /**
     * 编辑
     */
    public function edit()
    {
        $id  = $this->request->param($this->model->getPk());
        $row = $this->model->find($id);
        if (!$row) {
            $this->error(__('Record not found'));
        }

        $dataLimitAdminIds = $this->getDataLimitAdminIds();
        if ($dataLimitAdminIds && !in_array($row[$this->dataLimitField], $dataLimitAdminIds)) {
            $this->error(__('You have no permission'));
        }

        if ($this->request->isPost()) {
            $data = $this->request->post();
            if (!$data) {
                $this->error(__('Parameter %s can not be empty', ['']));
            }

            $data   = $this->excludeFields($data);
//            $sql="select  dbo.f_allow_truckno('$data[TZID]','$data[CNTRNO]','$data[TRUCKNO]') as status";
//            $status=Db::query($sql);
//            if($status){
//                $this->error('不能保存');
//            }
            $result = false;
            Db::startTrans();
            try {
                // 模型验证
                if ($this->modelValidate) {
                    $validate = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                    if (class_exists($validate)) {
                        $validate = new $validate;
                        if ($this->modelSceneValidate) $validate->scene('edit');
                        $validate->check($data);
                    }
                }
                $result = $row->save($data);
                Db::commit();
            } catch (ValidateException|PDOException|Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success(__('Update successful'));
            } else {
                $this->error(__('No rows updated'));
            }

        }

        $this->success('', [
            'row' => $row
        ]);
    }

    /**
     * 匹配罐箱分配货物匹配的箱号列表
     */
    public function box(){
        $tzid=$this->request->get('tzid');
//        $da=Db::query("select DISTINCT X_POTFPGOODS.TCNO from 	x_potfpgoods as X_POTFPGOODS,
//	x_potfp as X_POTFP,
//	x_potsq as X_POTSQ,
//tz as 	TZ
// where X_POTFP.TKID=X_POTSQ.TKID and X_POTSQ.TKID=X_POTFPGOODS.TKID and X_POTFPGOODS.GOODSID=TZ.CONTRACTNO  and TZ.TZID='$tzid'
//  and (X_POTFP.ENDDATE IS NULL OR
////   (X_POTFP.ENDDATE is not null and ENDDATE>GETDATE())
//  )");
        $da=Db::query("select DISTINCT X_POTFPGOODS.TCNO from 	x_potfpgoods as X_POTFPGOODS,
	x_potfp as X_POTFP,
	x_potsq as X_POTSQ,
tz as 	TZ 
 where X_POTFP.TKID=X_POTSQ.TKID and X_POTSQ.TKID=X_POTFPGOODS.TKID and X_POTFPGOODS.GOODSID=TZ.CONTRACTNO  and TZ.TZID='$tzid' 
  and (X_POTFP.ENDDATE IS NULL  )");
        $this->success('',$da);
    }

    /**
     * 车队
     */
    public function car(){
        $tzid=$this->request->get('tzid');
        $da=Db::query("select corp from customtype where code='TRUCK' and exists (select * from corplib where corplib.corp=customtype.corp and corplib.active='1')");
        $now=Db::query("SELECT MAX(X_BJCOST.VENDOR) FROM x_bjcost as X_BJCOST,x_bjline as X_BJLINE,customtype as CUSTOMTYPE,tz as TZ  WHERE X_BJCOST.LINEID=X_BJLINE.ID AND X_BJCOST.BJNO=TZ.BOOKINGNO 
            AND X_BJCOST.LOADPLACE=TZ.PORTLOAD AND X_BJCOST.DISPLACE=TZ.PORTDIS AND X_BJCOST.VENDOR=CUSTOMTYPE.CORP AND CUSTOMTYPE.CODE='TRUCK'
             AND TZ.TZID='$tzid'");

        $this->success('',['up'=>$da,'down'=>$now]);
    }

    /**
     * 提箱地址
     */
    public function tx(){
        $tzid=$this->request->get('tzid');
        $da=Db::query("select remind from area where port='堆场'");
        $now=Db::query("SELECT MAX(X_BJBODY.TXPLACE) FROM x_bjbody as X_BJBODY,x_bjline as X_BJLINE,tz as TZ  WHERE X_BJBODY.LINEID=X_BJLINE.ID AND X_BJBODY.BJNO=TZ.BOOKINGNO 
AND X_BJLINE.LOADPLACE=TZ.PORTLOAD AND X_BJLINE.DISPLACE=TZ.PORTDIS  AND TZ.TZID='$tzid'");

        $this->success('',['up'=>$da,'down'=>$now]);
    }

    /**
     * 回厂
     */
    public function hc(){
        $tzid=$this->request->get('tzid');
        $da=Db::query("select remind from area where port='堆场'");
        $now=Db::query("SELECT MAX(X_BJBODY.RETURNPLACE) FROM x_bjbody as X_BJBODY,x_bjline as X_BJLINE,tz as TZ WHERE X_BJBODY.LINEID=X_BJLINE.ID AND X_BJBODY.BJNO=TZ.BOOKINGNO 
AND X_BJLINE.LOADPLACE=TZ.PORTLOAD AND X_BJLINE.DISPLACE=TZ.PORTDIS  AND TZ.TZID='$tzid'");

        $this->success('',['up'=>$da,'down'=>$now]);
    }

    /**
     * 送货地址
     */
    public function sh(){
        $tzid=$this->request->get('tzid');
        $sender=$this->tz->where('TZID',$tzid)->value('sender');
        $da=Db::query("select remind from area where corp='$sender' and port='送货地'");
    }
}